package com.github.bridge.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.extra.cglib.CglibUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.dtflys.forest.callback.OnProgress;
import com.github.bridge.client.esign.ESignClient;
import com.github.bridge.client.esign.ESignResult;
import com.github.bridge.client.esign.request.*;
import com.github.bridge.client.esign.response.*;
import com.github.bridge.exception.CustomException;
import com.github.bridge.request.*;
import com.github.bridge.response.*;
import com.github.bridge.util.Const;
import com.github.bridge.util.ESignUtil;
import com.github.bridge.util.JacksonUtil;
import com.timevale.esign.paas.tech.bean.request.OrganizeParam;
import com.timevale.esign.paas.tech.bean.request.PersonParam;
import com.timevale.esign.paas.tech.bean.request.PersonSignParam;
import com.timevale.esign.paas.tech.bean.request.QueryAccountInfoParam;
import com.timevale.esign.paas.tech.bean.result.*;
import com.timevale.esign.paas.tech.client.ServiceClient;
import com.timevale.esign.paas.tech.client.ServiceClientManager;
import com.timevale.esign.paas.tech.enums.*;
import com.timevale.esign.paas.tech.service.AccountService;
import com.timevale.esign.paas.tech.service.TemplateSealService;
import com.timevale.esign.paas.tech.service.UserSignService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: signature-bridge-service
 * @description:
 * @author: hui.zhang
 * @date: 2024/8/25 11:09 上午
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class ESignHandler implements IServiceHandler {
    private final ESignClient eSignClient;
    private final Snowflake snowflake;
    private final SysConfigHandler sysConfigHandler;

    @Value("${e.sign.remarkDomain}")
    private String remarkDomain;
    @Value("${e.sign.sdkAppId}")
    private String appId;
    @Value("${e.sign.sdkAppSecret}")
    private String secret;
    @Value("${file.path}")
    private String filePath;
    @Value("${sso.account}")
    private String ssoAccount;

    public GeneratePdfFileVO generatePdfFile(GeneratePdfFileDTO dto) {
        // a0e6e3064a376d995bd87facb8926afd 测试 name zhanghui
        String systemId = dto.getSystemId();
        GeneratePdfFileRequest generatePdfFileRequest = CglibUtil.copy(dto, GeneratePdfFileRequest.class);
        CommonHerder commonHerder = ESignUtil.signBody(systemId, JacksonUtil.toJsonStrAll(generatePdfFileRequest));
        ESignResult<GeneratePdfFileResponse> eSignResult = eSignClient.generatePdfFile(commonHerder, generatePdfFileRequest);
        if (!eSignResult.success()) {
            throw new RuntimeException(eSignResult.getMessage());
        }
        GeneratePdfFileResponse data = eSignResult.getData();
        GeneratePdfFileVO generatePdfFileVO = new GeneratePdfFileVO();
        CglibUtil.copy(data, generatePdfFileVO);
        return generatePdfFileVO;

    }


    @SneakyThrows
    public UploadWithAuthVO uploadWithAuth(File file, UploadWithAuthDTO dto) {
        String systemId = dto.getSystemId();
        String hash = SecureUtil.sha256(file);
        dto.setHash(hash);
        CommonHerder commonHerder = ESignUtil.signBody(systemId, JacksonUtil.toJsonStr(dto));
        UploadWithAuthRequest uploadWithAuthRequest = CglibUtil.copy(dto, UploadWithAuthRequest.class);
        ESignResult<FileUploadResponse> eSignResult = eSignClient.uploadWithAuth(commonHerder, file, uploadWithAuthRequest);
        if (eSignResult.success()) {
            log.info("文件上传成功");
            FileUploadResponse data = eSignResult.getData();
            return CglibUtil.copy(data, UploadWithAuthVO.class);
        } else {
            log.error("文件上传失败");
            throw new RuntimeException(eSignResult.getMessage());
        }
    }

    public InputStream getFileStream(String fileKey, String systemId) {
        Map<String, String> map = MapUtil.builder("fileKey", fileKey).build();
        CommonHerder commonHerder = ESignUtil.signQuery(systemId, map);
        return eSignClient.getFileStream(commonHerder, fileKey);
    }

    public File downloadFile(String fileKey, String systemId, String dir, String filename, OnProgress onProgress) {
        Map<String, String> map = MapUtil.builder("fileKey", fileKey).build();
        CommonHerder commonHerder = ESignUtil.signQuery(systemId, map);
        return eSignClient.downloadFile(commonHerder, fileKey, dir, filename, onProgress);
    }

    public GetDownloadUrlVO getDownloadUrl(String fileKey, String systemId) {
        Map<String, String> map = MapUtil.builder("fileKey", fileKey).build();
        CommonHerder commonHerder = ESignUtil.signQuery(systemId, map);
        ESignResult<GetDownloadUrlResponse> eSignResult = eSignClient.getDownloadUrl(commonHerder, fileKey);
        if (eSignResult.success()) {
            GetDownloadUrlResponse data = eSignResult.getData();
            return CglibUtil.copy(data, GetDownloadUrlVO.class);
        } else {
            throw new RuntimeException(eSignResult.getMessage());
        }

    }

    @Override
    public CreateOuterOrgVO createOuterOrg(CreateOuterOrgDTO dto) {
        ServiceClient serviceClient = ServiceClientManager.get(Const.E_SIGN_APP_ID);
        AccountService accountService = serviceClient.accountService();
        OrganizeParam organizeParam = CglibUtil.copy(dto, OrganizeParam.class);
        organizeParam.setRegType(OrganRegTypeEnum.valueOf(dto.getRegType()));
        AddAccountResult addAccountResult = accountService.addAccount(organizeParam);
        boolean success = addAccountResult.success();
        if (success) {
            String accountId = addAccountResult.getAccountId();
            CreateOuterOrgVO createOuterOrgVO = new CreateOuterOrgVO();
            createOuterOrgVO.setAccountId(accountId);
            log.info("addAccountResult:{}", JacksonUtil.toJsonStr(addAccountResult));
            return createOuterOrgVO;
        } else {
            if (1500012 == addAccountResult.getErrCode()) {
                throw new CustomException(1500012, addAccountResult.getMsg());
            }
            throw new RuntimeException(addAccountResult.getMsg());
        }
    }

    @Override
    public CreateOuterUserVO createOuterUser(CreateOuterUserDTO dto) {
        ServiceClient serviceClient = ServiceClientManager.get(Const.E_SIGN_APP_ID);
        AccountService accountService = serviceClient.accountService();
        PersonParam personParam = CglibUtil.copy(dto, PersonParam.class);
        String idNoType = dto.getIdNoType();
        personParam.setIdNoType(IdNoTypeEnum.getByName(idNoType));
        AddAccountResult addAccountResult = accountService.addAccount(personParam);
        if (addAccountResult.success()) {
            CreateOuterUserVO createOuterUserVO = new CreateOuterUserVO();
            createOuterUserVO.setAccountId(addAccountResult.getAccountId());
            return createOuterUserVO;
        } else {
            if (1500012 == addAccountResult.getErrCode()) {
                throw new CustomException(1500012, addAccountResult.getMsg());
            }
            throw new RuntimeException(addAccountResult.getMsg());
        }
    }

    @Override
    public BaseVO deleteOuterUser(DeleteOuterUserDTO dto) {
        ServiceClient serviceClient = ServiceClientManager.get(Const.E_SIGN_APP_ID);
        AccountService accountService = serviceClient.accountService();
        String accountId = dto.getAccountId();
        Result result = accountService.deleteAccount(accountId);
        if (!result.success()) {
            throw new RuntimeException(result.getMsg());
        }
        return new BaseVO();
    }

    @Override
    public CreateOuterOrgSealVO createOuterOrgSeal(CreateOuterOrgSealDTO dto) {
        ServiceClient serviceClient = ServiceClientManager.get(Const.E_SIGN_APP_ID);
        TemplateSealService templateSealService = serviceClient.templateSealService();
        // String accountId,OrganizeTemplateType type,String roundText,List<String> hTexts,String qText,SealColor color
        OrganizeTemplateType organizeTemplateType = OrganizeTemplateType.valueOf(dto.getType());
        SealColor sealColor = SealColor.valueOf(dto.getColor());
        AddSealResult addSealResult = templateSealService.createOrgSeal(dto.getAccountId(), organizeTemplateType, dto.getRoundText(), dto.getHTexts(), dto.getQText(), sealColor);
        if (addSealResult.success()) {
            CreateOuterOrgSealVO createOuterOrgSealVO = new CreateOuterOrgSealVO();
            createOuterOrgSealVO.setSealData(addSealResult.getSealData());
            return createOuterOrgSealVO;
        } else {
            throw new RuntimeException(addSealResult.getMsg());
        }
    }

    @Override
    public CreateOuterUserSealVO createOuterUserSeal(CreateOuterUserSealDTO dto) {
        ServiceClient serviceClient = ServiceClientManager.get(Const.E_SIGN_APP_ID);
        TemplateSealService templateSealService = serviceClient.templateSealService();
        // TemplateSealService.createPsnSeal(String accountId,String name,PersonTemplateType type,SealColor color, StampRuleEnum stampRule)
        AddSealResult addSealResult = templateSealService.createPsnSeal(dto.getAccountId(), dto.getName(), PersonTemplateType.valueOf(dto.getType()), SealColor.valueOf(dto.getColor()), StampRuleEnum.valueOf(dto.getStampRule()));
        if (addSealResult.success()) {
            CreateOuterUserSealVO createOuterUserSealVO = new CreateOuterUserSealVO();
            createOuterUserSealVO.setSealData(addSealResult.getSealData());
            return createOuterUserSealVO;
        } else {
            throw new RuntimeException(addSealResult.getMsg());
        }
    }

    @Override
    public OuterUserSignatureVO outerUserSignature(OuterUserSignatureDTO dto) {
        log.info("外部用户签章账号id:{},fileKey:{}", dto.getAccountId(), dto.getFileBean().getFileKey());
        ServiceClient serviceClient = ServiceClientManager.get(Const.E_SIGN_APP_ID);
        UserSignService userSignService = serviceClient.userSignService();
        PersonSignParam personSignParam = new PersonSignParam();
        BeanUtil.copyProperties(dto, personSignParam);
        personSignParam.setSealSpec(SealSpecEnum.valueOf(dto.getSealSpec()));
        // 文件下载后存放在临时目录
        String fileKey = dto.getFileBean().getFileKey();
        long nextId = snowflake.nextId();
        String randomStr = RandomUtil.randomString(6);
        String fileName = nextId + "-" + randomStr + ".pdf";
        String dstName = nextId + "-" + randomStr + "_dst" + ".pdf";
        File file = downloadFile(fileKey, dto.getSystemId(), filePath, fileName, progress -> {
            log.info("total bytes:{}", progress.getTotalBytes());   // 文件大小
            log.info("current bytes:{}", progress.getCurrentBytes());   // 已下载字节数
            log.info("progress:{}", Math.round(progress.getRate() * 100) + "%");  // 已下载百分比
            if (progress.isDone()) {   // 是否下载完成
                log.info("Download Completed!");
            }
        });
        FileInputStream fileInputStream = null;
        FileInputStream dstFileInputStream = null;
        log.info("src文件生成:{}", file.getAbsolutePath());
        File dstFile = FileUtil.file(filePath, dstName);
        log.info("dst文件路径:{}", dstFile.getAbsolutePath());
        try {
            log.info("签署前文件大小:{}", FileUtil.size(file));
            Digester digester = SecureUtil.sha256();
            fileInputStream = new FileInputStream(file);
            byte[] digest = digester.digest(fileInputStream);
            String encode = Base64.encode(digest);
            log.info("签署前文件hash:{}", encode);
            personSignParam.getFileBean().setSrcPdfFile(file.getAbsolutePath());
            personSignParam.getFileBean().setDstPdfFile(dstFile.getAbsolutePath());
            FileDigestSignResult fileDigestSignResult = userSignService.personSign(personSignParam);
            if (fileDigestSignResult.success()) {
                log.info("签署后文件大小:{}", FileUtil.size(dstFile));
                Digester dstDigester = SecureUtil.sha256();
                dstFileInputStream = new FileInputStream(dstFile);
                byte[] dstDigest = dstDigester.digest(dstFileInputStream);
                log.info("签署后文件hash:{}", Base64.encode(dstDigest));
                OuterUserSignatureVO outerUserSignatureVO = new OuterUserSignatureVO();
                CglibUtil.copy(fileDigestSignResult, outerUserSignatureVO);
                log.info("外部用户签署成功 上传oss获取fileKey:{}", JSONUtil.toJsonStr(outerUserSignatureVO));
                UploadWithAuthDTO uploadWithAuthDTO = new UploadWithAuthDTO();
                uploadWithAuthDTO.setFilePwd(dto.getFileBean().getPassword());
                uploadWithAuthDTO.setSystemId(dto.getSystemId());
                UploadWithAuthVO vo = this.uploadWithAuth(new File(outerUserSignatureVO.getDstFilePath()), uploadWithAuthDTO);
                log.info("uploadWithAuthVO:{}", JacksonUtil.toJsonStr(vo));
                if (vo == null || StrUtil.isBlank(vo.getFileKey())) {
                    throw new RuntimeException("上传oss失败");
                } else {
                    CglibUtil.copy(vo, outerUserSignatureVO);
                }
                return outerUserSignatureVO;
            } else {
                log.error("sdk外部签署失败");
                throw new RuntimeException(fileDigestSignResult.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            IoUtil.close(dstFileInputStream);
            IoUtil.close(fileInputStream);
            log.info("删除临时下载的原文件");
            FileUtil.del(file);
            log.info("删除外部签署后的的目标文件");
            FileUtil.del(dstFile);
        }
    }

    @Override
    public OuterOrgSignatureVO outerOrgSignature(OuterUserSignatureDTO dto) {

        return null;
    }


    @Override
    public InnerSignatureVO innerSignature(InnerSignatureDTO dto) {
        String systemId = dto.getSystemId();
        CreateAndStartRequest createAndStartRequest = BeanUtil.copyProperties(dto, CreateAndStartRequest.class);
        CommonHerder commonHerder = ESignUtil.signBody(systemId, JacksonUtil.toJsonStrAll(createAndStartRequest));
        ESignResult<CreateAndStartResponse> eSignResult = eSignClient.createAndStart(commonHerder, createAndStartRequest);
        if (eSignResult.success()) {
            InnerSignatureVO innerSignatureVO = new InnerSignatureVO();
            CglibUtil.copy(eSignResult.getData(), innerSignatureVO);
            return innerSignatureVO;
        } else {
            throw new RuntimeException(eSignResult.getMessage());
        }
    }

    @Override
    public CreateUserAndSealVO createUserAndSeal(CreateUserAndSealDTO dto) {
        ServiceClient serviceClient = ServiceClientManager.get(Const.E_SIGN_APP_ID);
        AccountService accountService = serviceClient.accountService();
        PersonParam personParam = CglibUtil.copy(dto, PersonParam.class);
        String idNoType = dto.getIdNoType();
        personParam.setIdNoType(IdNoTypeEnum.getByName(idNoType));
        AddAccountResult addAccountResult = accountService.addAccount(personParam);
        if (addAccountResult.success()) {
            String accountId = addAccountResult.getAccountId();
            TemplateSealService templateSealService = serviceClient.templateSealService();
            AddSealResult addSealResult = templateSealService.createPsnSeal(accountId, "", PersonTemplateType.valueOf(dto.getType()), SealColor.valueOf(dto.getColor()), StampRuleEnum.valueOf(dto.getStampRule()));
            if (addSealResult.success()) {
                CreateUserAndSealVO createUserAndSealVO = new CreateUserAndSealVO();
                createUserAndSealVO.setAccountId(accountId);
                createUserAndSealVO.setSealData(addSealResult.getSealData());
                return createUserAndSealVO;
            } else {
                throw new RuntimeException(addSealResult.getMsg());
            }

        } else {
            if (1500012 == addAccountResult.getErrCode()) {
                throw new CustomException(1500012, addAccountResult.getMsg());
            }
            throw new RuntimeException(addAccountResult.getMsg());
        }
    }

    @Override
    public AccountInfoResult getAccountInfo(QueryAccountInfoParam queryAccountInfoParam) {
        ServiceClient serviceClient = ServiceClientManager.get(Const.E_SIGN_APP_ID);
        AccountService accountService = serviceClient.accountService();
        AccountInfoResult accountInfo = accountService.getAccountInfo(queryAccountInfoParam);
        log.info("用户信息:{}", JSONUtil.toJsonStr(accountInfo));
        return accountInfo;
    }

    @Override
    public SignDetailVO signDetail(SignDetailDTO dto) {
        String systemId = dto.getSystemId();
        SignDetailRequest signDetailRequest = CglibUtil.copy(dto, SignDetailRequest.class);
        Map<String, String> map = new HashMap<>();
        if (StrUtil.isNotBlank(dto.getSignFlowId())) {
            map.put("signFlowId", dto.getSignFlowId());
        }
        if (StrUtil.isNotBlank(dto.getBusinessNo())) {
            map.put("businessNo", dto.getBusinessNo());
        }
        CommonHerder commonHerder = ESignUtil.signQuery(systemId, map);
        ESignResult<SignDetailResponse> eSignResult = eSignClient.signDetail(commonHerder, signDetailRequest);
        if (eSignResult.success()) {
            SignDetailVO vo = new SignDetailVO();
            SignDetailResponse data = eSignResult.getData();
            CglibUtil.copy(data, vo);
            return vo;
        } else {
            throw new RuntimeException(eSignResult.getMessage());
        }
    }

    @Override
    public OuterUserSignatureVO outerUserCreateAndSignature(OuterUserCreateAndSignatureDTO dto) {
        CreateUserAndSealDTO createUserAndSealDTO = new CreateUserAndSealDTO();
        CglibUtil.copy(dto, createUserAndSealDTO);
        CreateUserAndSealVO userAndSeal = null;
        try {
            userAndSeal = createUserAndSeal(createUserAndSealDTO);
        } catch (Exception e) {
            if (e instanceof CustomException) {
                if (1500012 == ((CustomException) e).getCode()) {
                    // 查询已经绑定的用户信息
                    QueryAccountInfoParam queryAccountInfoParam = new QueryAccountInfoParam();
                    queryAccountInfoParam.setIdNoType(AllIdNoTypeEnum.getByName(dto.getIdNoType()));
                    queryAccountInfoParam.setIdNo(dto.getIdNo());
                    queryAccountInfoParam.setEncrypt(dto.getEncrypt());
                    queryAccountInfoParam.setType(AccountTypeEnum.PERSON);
                    AccountInfoResult accountInfo = getAccountInfo(queryAccountInfoParam);
                    throw new CustomException(1500012, accountInfo.getAccountId());
                }
            }
            throw new RuntimeException(e);
        }
        String accountId = userAndSeal.getAccountId();
        String sealData = userAndSeal.getSealData();

        OuterUserSignatureDTO outerUserSignatureDTO = new OuterUserSignatureDTO();
        CglibUtil.copy(dto, outerUserSignatureDTO);
        outerUserSignatureDTO.setAccountId(accountId);
        outerUserSignatureDTO.setSealData(sealData);
        outerUserSignatureDTO.setSealSpec("IMAGE");
        return outerUserSignature(outerUserSignatureDTO);
    }

    @Override
    public CreateOrgAndSealVO createOrgAndSeal(CreateOrgAndSealDTO dto) {
        ServiceClient serviceClient = ServiceClientManager.get(Const.E_SIGN_APP_ID);
        AccountService accountService = serviceClient.accountService();
        OrganizeParam organizeParam = CglibUtil.copy(dto, OrganizeParam.class);
        String regType = dto.getRegType();
        organizeParam.setRegType(OrganRegTypeEnum.valueOf(regType));
        AddAccountResult addAccountResult = accountService.addAccount(organizeParam);
        if (addAccountResult.success()) {
            String accountId = addAccountResult.getAccountId();
            TemplateSealService templateSealService = serviceClient.templateSealService();
            AddSealResult addSealResult = templateSealService.createOrgSeal(accountId, OrganizeTemplateType.getByName(dto.getType()), dto.getRoundText(), dto.getHTexts(), dto.getQText(), SealColor.getByName(dto.getColor()));
            if (addSealResult.success()) {
                CreateOrgAndSealVO createOrgAndSealVO = new CreateOrgAndSealVO();
                createOrgAndSealVO.setAccountId(accountId);
                createOrgAndSealVO.setSealData(addSealResult.getSealData());
                return createOrgAndSealVO;
            } else {
                throw new RuntimeException(addSealResult.getMsg());
            }
        } else {
            if (1500012 == addAccountResult.getErrCode()) {
                throw new CustomException(1500012, addAccountResult.getMsg());
            }
            throw new RuntimeException(addAccountResult.getMsg());
        }
    }

    public CreateRemarkUrlVO createRemarkUrl(CreateRemarkUrlDTO dto) {

       return null;

    }

//    public static void main(String[] args) {
//        String json = "{\n" +
//                "    \"inputType\": \"1\",\n" +
//                "    \"remarkContent\": \"我已经阅读并悉知\",\n" +
//                "    \"remarkFieldWidth\": \"300\",\n" +
//                "    \"remarkFieldHeight\": \"100\",\n" +
//                "    \"aiCheck\": \"1\",\n" +
//                "    \"notifyUrl\": \"\",\n" +
//                "    \"redirectUrl\": \"\"\n" +
//                "}";
//        byte[] bytes = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, "ea1555ad8df3628cac029f54d3236086").hmac(json);
//        String signature = new String(Hex.encodeHex(bytes));
//
//        Object signature1 = Forest.post("https://smlopenapi.esign.cn/v3/remark-url")
//                .addHeader("Content-Type", "application/json; charset=UTF-8")
//                .addHeader("X-Tsign-Open-Ca-Timestamp", System.currentTimeMillis())
//                .addHeader("X-Tsign-Open-App-Id", "7438996506")
//                .addHeader("X-Tsign-Open-Auth-Mode", "Signature")
//                .addHeader("X-Tsign-Open-Ca-Signature", signature)
//                .addHeader("Content-MD5", SecureUtil.md5(json))
//                .addBody(json).execute();
//        System.out.println(signature1);
//    }

    public TemplateContentVO templateContent(TemplateContentDTO dto) {
        String systemId = dto.getSystemId();
        TemplateContentRequest templateContentRequest = BeanUtil.copyProperties(dto, TemplateContentRequest.class);
        CommonHerder commonHerder = ESignUtil.signBody(systemId, JacksonUtil.toJsonStrAll(templateContentRequest));
        ESignResult<TemplateContentResponse> eSignResult = eSignClient.templateContent(commonHerder, templateContentRequest);
        if (eSignResult.success()) {
            TemplateContentVO templateContentVO = new TemplateContentVO();
            CglibUtil.copy(eSignResult.getData(), templateContentVO);
            return templateContentVO;
        } else {
            throw new RuntimeException(eSignResult.getMessage());
        }
    }

    public PdfPreviewUrlVO pdfPreviewUrl(PdfPreviewUrlDTO dto) {
        String systemId = dto.getSystemId();
        PdfPreviewUrlRequest pdfPreviewUrlRequest = BeanUtil.copyProperties(dto, PdfPreviewUrlRequest.class);
        CommonHerder commonHerder = ESignUtil.signBody(systemId, JacksonUtil.toJsonStrAll(pdfPreviewUrlRequest));
        ESignResult<PdfPreviewUrlResponse> eSignResult = eSignClient.pdfPreviewUrl(commonHerder, pdfPreviewUrlRequest);
        if (eSignResult.success()) {
            PdfPreviewUrlVO pdfPreviewUrlVO = new PdfPreviewUrlVO();
            CglibUtil.copy(eSignResult.getData(), pdfPreviewUrlVO);

            // 这里处理免登录
            String secret = sysConfigHandler.findSecretBySystemId(systemId);
            Map<String, Object> map = new HashMap<>();
            map.put("clientId", systemId);
            map.put("clientSecret", secret);
            ESignResult<Map<String, String>> signClientAccessToken = eSignClient.getAccessToken(map);
            String accessToken = signClientAccessToken.getData().get("accessToken");
            if (!signClientAccessToken.success()) {
                throw new RuntimeException(signClientAccessToken.getMessage());
            }

            // 短链 需要获取下长链接
            String templatePreviewUrl = pdfPreviewUrlVO.getTemplatePreviewUrl();
            HttpResponse execute = HttpRequest.get(templatePreviewUrl).execute();
            String url = execute.header("location");
            Map<String, Object> ssoMap = new HashMap<>();
            ssoMap.put("accessToken", accessToken);
            ssoMap.put("clientId", systemId);
            AES aes = SecureUtil.aes(secret.getBytes(StandardCharsets.UTF_8));
            String account = aes.encryptBase64(ssoAccount);
            ssoMap.put("loginAccount", account);
            ssoMap.put("redirectUrl", url);
            ESignResult<Map<String, String>> ssoToken = eSignClient.getSsoToken(ssoMap);
            if (!ssoToken.success()) {
                throw new RuntimeException(ssoToken.getMessage());
            }
            pdfPreviewUrlVO.setTemplatePreviewUrlNotLogin(ssoToken.getData().get("ssoRedirectUrl"));
            return pdfPreviewUrlVO;
        } else {
            throw new RuntimeException(eSignResult.getMessage());
        }
    }
}
